<script setup lang="ts">
import { computed, onMounted, ref } from 'vue';
import dayjs from 'dayjs';
import type { Dayjs } from 'dayjs';
import { useEcharts } from '@/hooks/common/echarts';
import { getPersonWorkLoadData } from '@/service/api/modules/workwear/mold-data-statistics';

defineOptions({
  name: 'LineChart'
});
const loading = ref(false);
const keys = [
  'midnightToFourAm',
  'fourAmToEightAm',
  'eightAmToNoon',
  'noonToFourPm',
  'fourPmToEightPm',
  'eightPmToMidnight'
];

const dateFormat = 'YYYY-MM';

const month = ref<Dayjs>(dayjs(dayjs().format('YYYY-MM'), dateFormat));

const { domRef, updateOptions } = useEcharts(
  () => ({
    tooltip: {
      trigger: 'item'
    },
    legend: {
      bottom: '5%',
      left: 'center'
    },
    title: {
      text: `${month.value.format('YYYY年MM')}月人员工作量统计`,
      left: 'center',
      top: 0
    },
    series: [
      {
        name: '人员工作量统计',
        type: 'pie',
        radius: ['40%', '70%'],
        avoidLabelOverlap: false,
        padAngle: 5,
        itemStyle: {
          borderRadius: 10
        },
        label: {
          show: false,
          position: 'center'
        },
        emphasis: {
          label: {
            show: true,
            fontSize: 40,
            fontWeight: 'bold'
          }
        },
        labelLine: {
          show: false
        },
        data: []
      }
    ]
  }),
  false
);

function getData() {
  loading.value = true;
  getPersonWorkLoadData({
    yearMonth: month.value.format('YYYY-MM')
  })
    .then(({ data, error }) => {
      if (!error) {
        const chartData = data.map(item => {
          return {
            name: item.operator,
            value: item.punchNum
          };
        });
        updateOptions(opts => {
          opts.series[0].data = chartData;
          return opts;
        });
      }
    })
    .finally(() => {
      loading.value = false;
    });
}

function handleMonthChange(date: Dayjs) {
  updateOptions(opts => {
    opts.title.text = `${date.format('YYYY年MM')}月报废数据统计`;

    return opts;
  });
  getData();
}

onMounted(() => {
  getData();
});
</script>

<template>
  <ACard :bordered="false" class="card-wrapper">
    <ASpin tip="数据加载中..." :spinning="loading">
      <div ref="domRef" class="h-full overflow-hidden"></div>
      <div class="select-month">
        <ADatePicker
          v-model:value="month"
          picker="month"
          :allow-clear="false"
          size="small"
          format="YYYY-MM"
          @change="handleMonthChange"
        />
      </div>
    </ASpin>
  </ACard>
</template>

<style scoped>
.select-month {
  position: absolute;
  top: 0px;
  left: 10px;
}
</style>
